<?php
class WCatalog extends CWidget
{
    
    public function run() {
        if (isset($_GET['url'])){
            
                $category_model = $this->loadCategory($_GET['url']);
                $catalog_model = $this->loadCatalog($category_model['id']);
        }else{
                $catalog_model = $this->loadCatalog();
        }
        $this->render('wcatalog',array(
            'category' => $category_model,
            'catalog_model'=>$catalog_model
        ));
        
    }
    
    private function loadCategory($url){
        $model = CatalogCategory::getCategoryByUrl($url);
        if(count($model)==0)
                throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }
    
    private function loadCatalog($catalog_id=null){
        if ($catalog_id == null){
            $model = Catalog::getAllCatalog();
        }else
        {
            $model = Catalog::getCatalogByCategory($catalog_id);
        }
        if(count($model)==0)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
//return $this->loadFieldsByCatalog($model);
    }
    
    private function loadFieldsByCatalog($model){
        foreach ($model as $key=>$value) {
                    $model[$key]['custom_fields'] = 
                    CatalogCustomFields::getFieldsAndValueOfCategoryCurrentLanguage($value['catalog_category_id']);
                }
        return $model;
    }
}